'use client';

import React, { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import { io, Socket } from 'socket.io-client';
import { TokenData } from '../types/token';

interface WebSocketContextType {
  socket: Socket | null;
  isConnected: boolean;
  isMonitoring: boolean;
  tokens: TokenData[];
  startMonitoring: () => void;
  stopMonitoring: () => void;
  lastUpdate: string | null;
}

const WebSocketContext = createContext<WebSocketContextType>({
  socket: null,
  isConnected: false,
  isMonitoring: false,
  tokens: [],
  startMonitoring: () => {},
  stopMonitoring: () => {},
  lastUpdate: null,
});

export const useWebSocket = () => {
  const context = useContext(WebSocketContext);
  if (!context) {
    throw new Error('useWebSocket must be used within a WebSocketProvider');
  }
  return context;
};

interface WebSocketProviderProps {
  children: ReactNode;
}

export const WebSocketProvider: React.FC<WebSocketProviderProps> = ({ children }) => {
  const [socket, setSocket] = useState<Socket | null>(null);
  const [isConnected, setIsConnected] = useState(false);
  const [isMonitoring, setIsMonitoring] = useState(false);
  const [tokens, setTokens] = useState<TokenData[]>([]);
  const [lastUpdate, setLastUpdate] = useState<string | null>(null);

  // 获取初始代币数据
  const fetchInitialTokens = async () => {
    try {
      console.log('获取初始代币数据...');
      const response = await fetch('/api/tokens');
      if (response.ok) {
        const data = await response.json();
        console.log('获取到初始代币数据:', data);
        setTokens(data);
      }
    } catch (error) {
      console.error('获取初始代币数据失败:', error);
    }
  };

  useEffect(() => {
    // 立即获取初始数据
    fetchInitialTokens();

    // 创建Socket.IO连接
    const socketInstance = io(process.env.NODE_ENV === 'production' ? '' : 'http://localhost:3000', {
      transports: ['websocket', 'polling'],
    });

    setSocket(socketInstance);

    // 连接事件处理
    socketInstance.on('connect', () => {
      console.log('WebSocket已连接');
      setIsConnected(true);
      // 连接成功后再次获取最新数据
      fetchInitialTokens();
    });

    socketInstance.on('disconnect', () => {
      console.log('WebSocket已断开连接');
      setIsConnected(false);
      setIsMonitoring(false);
    });

    // 监控状态更新
    socketInstance.on('monitoring-status', (data: { isMonitoring: boolean }) => {
      console.log('监控状态更新:', data);
      setIsMonitoring(data.isMonitoring);
    });

    // 价格数据更新
    socketInstance.on('price-update', (data: { tokens: TokenData[]; timestamp: string }) => {
      console.log('收到价格更新:', data);
      setTokens(data.tokens);
      setLastUpdate(data.timestamp);
    });

    // 价格更新错误
    socketInstance.on('price-update-error', (data: { error: string; timestamp: string }) => {
      console.error('价格更新错误:', data);
      setLastUpdate(data.timestamp);
    });

    // 清理函数
    return () => {
      socketInstance.disconnect();
    };
  }, []);

  const startMonitoring = () => {
    if (socket && isConnected) {
      socket.emit('start-monitoring');
    }
  };

  const stopMonitoring = () => {
    if (socket && isConnected) {
      socket.emit('stop-monitoring');
    }
  };

  const contextValue: WebSocketContextType = {
    socket,
    isConnected,
    isMonitoring,
    tokens,
    startMonitoring,
    stopMonitoring,
    lastUpdate,
  };

  return (
    <WebSocketContext.Provider value={contextValue}>
      {children}
    </WebSocketContext.Provider>
  );
};
